#!/usr/bin/env python

"""Namelist creator for CIME's data ocn model.
"""

# Typically ignore this.
# pylint: disable=invalid-name

# Disable these because this is our standard setup
# pylint: disable=wildcard-import,unused-wildcard-import,wrong-import-position

import os, sys, glob, re

_CIMEROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..","..","..","..","..")
sys.path.append(os.path.join(_CIMEROOT, "scripts", "Tools"))

from standard_script_setup import *
from CIME.case import Case
from CIME.XML.files import Files
from CIME.nmlgen import NamelistGenerator
from CIME.utils import expect, safe_copy
from CIME.buildnml import create_namelist_infile, parse_input

logger = logging.getLogger(__name__)

# pylint: disable=too-many-arguments,too-many-locals,too-many-branches,too-many-statements
####################################################################################
def _create_namelists(case, confdir, inst_string, infile, nmlgen, data_list_path):
####################################################################################
    """Write out the namelist for this component.

    Most arguments are the same as those for `NamelistGenerator`. The
    `inst_string` argument is used as a suffix to distinguish files for
    different instances. The `confdir` argument is used to specify the directory
    in which output files will be placed.
    """

    #----------------------------------------------------
    # Get a bunch of information from the case.
    #----------------------------------------------------
    ocn_domain_file = case.get_value("OCN_DOMAIN_FILE")
    ocn_domain_path = case.get_value("OCN_DOMAIN_PATH")
    docn_mode = case.get_value("DOCN_MODE")
    ocn_grid = case.get_value("OCN_GRID")
    sstice_stream = case.get_value("SSTICE_STREAM")

    #----------------------------------------------------
    # Check for incompatible options.
    #----------------------------------------------------
    expect(ocn_grid != "null",
           "OCN_GRID cannot be null")
    expect(docn_mode != "NULL",
           "DOCN_MODE cannot be NULL")

    #----------------------------------------------------
    # Log some settings.
    #----------------------------------------------------
    logger.debug("DOCN mode is {}".format(docn_mode))
    logger.debug("DOCN grid is {}".format(ocn_grid))

    #----------------------------------------------------
    # Create configuration information.
    #----------------------------------------------------
    config = {}
    config['ocn_grid'] = ocn_grid
    config['docn_mode'] = docn_mode
    config['sstice_stream'] = sstice_stream

    #----------------------------------------------------
    # Initialize namelist defaults
    #----------------------------------------------------
    nmlgen.init_defaults(infile, config)

    #----------------------------------------------------
    # Construct the list of streams.
    #----------------------------------------------------
    streams = nmlgen.get_streams()

    #----------------------------------------------------
    # For each stream, create stream text file and update
    # shr_strdata_nml group and input data list.
    #----------------------------------------------------
    for stream in streams:

        # Ignore null values.
        if stream is None or stream in ("NULL", ""):
            continue

        inst_stream = stream + inst_string
        logger.debug("DOCN stream is {}".format(inst_stream))
        stream_path = os.path.join(confdir, "docn.streams.txt." + inst_stream)
        nmlgen.create_stream_file_and_update_shr_strdata_nml(config, case.get_value("CASEROOT"), stream, stream_path, data_list_path)

    # For aquaplanet prescribed have no streams
    match = re.match(r'^sst_aquap\d+',docn_mode)
    if match is not None:
        if match.group(0):
            value = ['null']
            nmlgen.set_value("streams",value)

    # globally uniform SST mode
    if docn_mode=='sst_aquap_constant':
        value = ['null']
        nmlgen.set_value("streams",value)
        value = [case.get_value('DOCN_AQPCONST_VALUE')]
        nmlgen.set_value("sst_constant_value",value)
    #----------------------------------------------------
    # Create `shr_strdata_nml` namelist group.
    #----------------------------------------------------
    # set per-stream variables
    nmlgen.create_shr_strdata_nml()

    # set variables that are not per-stream
    if ocn_domain_file != "UNSET":
        full_domain_path = os.path.join(ocn_domain_path, ocn_domain_file)
        nmlgen.add_default("domainfile", value=full_domain_path)
    else:
        if "aqua" in docn_mode:
            expect( ocn_domain_file != "UNSET",
                    "in aquaplanet mode the xml variable OCN_DOMAIN_FILE cannot be equal to UNSET ")
        else:
            nmlgen.add_default("domainfile", value='null')

    #----------------------------------------------------
    # Finally, write out all the namelists.
    #----------------------------------------------------
    namelist_file = os.path.join(confdir, "docn_in")
    nmlgen.write_output_file(namelist_file, data_list_path, groups=['docn_nml','shr_strdata_nml'])

###############################################################################
def buildnml(case, caseroot, compname):
###############################################################################

    # Build the component namelist and required stream txt files
    if compname != "docn":
        raise AttributeError

    rundir = case.get_value("RUNDIR")
    ninst = case.get_value("NINST_OCN")
    if ninst is None:
        ninst = case.get_value("NINST")

    # Determine configuration directory
    confdir = os.path.join(caseroot,"Buildconf",compname + "conf")
    if not os.path.isdir(confdir):
        os.makedirs(confdir)

    #----------------------------------------------------
    # Construct the namelist generator
    #----------------------------------------------------
    # determine directory for user modified namelist_definitions.xml
    user_xml_dir = os.path.join(caseroot, "SourceMods", "src." + compname)
    expect (os.path.isdir(user_xml_dir),
            "user_xml_dir {} does not exist ".format(user_xml_dir))

    # NOTE: User definition *replaces* existing definition.
    files = Files()
    definition_file = [files.get_value("NAMELIST_DEFINITION_FILE", {"component":"docn"})]

    user_definition = os.path.join(user_xml_dir, "namelist_definition_docn.xml")
    if os.path.isfile(user_definition):
        definition_file = [user_definition]
    for file_ in definition_file:
        expect(os.path.isfile(file_), "Namelist XML file {} not found!".format(file_))

    # Create the namelist generator object - independent of instance
    nmlgen = NamelistGenerator(case, definition_file, files=files)

    #----------------------------------------------------
    # Clear out old data.
    #----------------------------------------------------
    data_list_path = os.path.join(case.get_case_root(), "Buildconf",
                                  "docn.input_data_list")
    if os.path.exists(data_list_path):
        os.remove(data_list_path)

    #----------------------------------------------------
    # Loop over instances
    #----------------------------------------------------
    for inst_counter in range(1, ninst+1):
        # determine instance string
        inst_string = ""
        if ninst > 1:
            inst_string = '_' + "{:04d}".format(inst_counter)

        # If multi-instance case does not have restart file, use
        # single-case restart for each instance
        rpointer = "rpointer." + compname
        if (os.path.isfile(os.path.join(rundir,rpointer)) and
            (not os.path.isfile(os.path.join(rundir,rpointer + inst_string)))):
            safe_copy(os.path.join(rundir, rpointer),
                      os.path.join(rundir, rpointer + inst_string))

        inst_string_label = inst_string
        if not inst_string_label:
            inst_string_label = "\"\""

        # create namelist output infile using user_nl_file as input
        user_nl_file = os.path.join(caseroot, "user_nl_" + compname + inst_string)
        expect(os.path.isfile(user_nl_file),
               "Missing required user_nl_file {} ".format(user_nl_file))
        infile = os.path.join(confdir, "namelist_infile")
        create_namelist_infile(case, user_nl_file, infile)
        namelist_infile = [infile]

        # create namelist and stream file(s) data component
        _create_namelists(case, confdir, inst_string, namelist_infile, nmlgen, data_list_path)

        # copy namelist files and stream text files, to rundir
        if os.path.isdir(rundir):
            filename = compname + "_in"
            file_src  = os.path.join(confdir, filename)
            file_dest = os.path.join(rundir, filename)
            if inst_string:
                file_dest += inst_string
            safe_copy(file_src,file_dest)

            for txtfile in glob.glob(os.path.join(confdir, "*txt*")):
                safe_copy(txtfile, rundir)

###############################################################################
def _main_func():
    # Build the component namelist and required stream txt files
    caseroot = parse_input(sys.argv)
    with Case(caseroot) as case:
        buildnml(case, caseroot, "docn")

if __name__ == "__main__":
    _main_func()
